package service

import (
	"blog/config"
	"blog/dao"
	"blog/models"
)

func GetPostDetail(pId int) (postDetail models.PostDetail, err error) {
	postMore, err := dao.GetPostMoreByPId(pId)
	postDetail.Viewer = config.Cfg.Viewer
	postDetail.SystemConfig = config.Cfg.System
	postDetail.Article = postMore
	dao.IncrementPostViewCountByPId(pId)
	return postDetail, err
}

func SavePost(post *models.Post) {
	dao.SavePost(post)
}
func UpdatePost(post *models.Post) {
	dao.UpdatePost(post)
}

func FindPostPigeonhole() (p models.PigeonholeResponse) {
	postAll, _ := dao.GetPostAll()
	pigeonholeMap := make(map[string][]models.Post)
	for _, post := range postAll {
		ca := post.CreateAt
		month := ca.Format("2006-01")
		pigeonholeMap[month] = append(pigeonholeMap[month], post)
	}
	categorys, _ := dao.GetAllCategory()
	return models.PigeonholeResponse{
		config.Cfg.Viewer,
		config.Cfg.System,
		categorys,
		pigeonholeMap,
	}
}

func SearchPost(condition string) []models.SearchResponse {
	posts, _ := dao.GetPostSearch(condition)
	var searchResponse []models.SearchResponse
	for _, post := range posts {
		searchResponse = append(searchResponse, models.SearchResponse{
			Pid:   post.Pid,
			Title: post.Title,
		})
	}
	return searchResponse
}
